<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="/WEB-INF/tld/c.tld"%>
<%@ taglib prefix="my" uri="/WEB-INF/tld/my.tld"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>${projectName}-新增原型</title>
<jsp:include page="/WEB-INF/view/inc/css.jsp"></jsp:include>
</head>
<body class="cld-body">
	<div class="enter-panel ep-sm">
		<input type="hidden" id="aiId" value="${param.aiId}"/>
		<input type="hidden" id="aaId" value="${param.aaId}"/>
		<input type="hidden" id="parentAaId" value="${appAnt.parentAaId}"/>
  		<div class="form-group">
			<label for="name" class="col-sm-4">名称 <span class="text-danger">*</span></label>
			<div class="col-sm-8"><input type="text" class="form-control" id="name" placeholder="名称" value="${appAnt.name}"></div>
		</div>
  		<div class="form-group">
			<label for="remark" class="col-sm-4">备注</label>
			<div class="col-sm-8"><input type="text" class="form-control" id="remark" placeholder="备注" value="${appAnt.remark}"></div>
		</div>
		<div class="form-group">
			<label for="type" class="col-sm-4 va-top">类型</label>
			<div class="col-sm-8"><my:radio id="type" name="type" dictcode="app_ant_type" value="${appAnt.type}" defvalue="20" exp="onclick=\"info.changeType($(this).val())\"" />
				<input type="hidden" id="typeValue" value="${appAnt.typeValue}">
				<div id="imgPanel">
					<input type="text" class="form-control" id="imgPaste" placeholder="点击我，ctrl+v直接粘贴上传图片" value="">
					<img id="imgFile" style="max-width: 300px;margin-top: 5px;" alt="原型图" src="${webroot}/resources/images/no_img.jpg"/>
				</div>
				<div id="urlPanel">
					<input type="text" class="form-control" id="urlValue" placeholder="点击我，输入原型地址" value="">
				</div>
			</div>
		</div>
		<hr/>
		<div class="form-group">
			<label for="apiType" class="col-sm-4 va-top">接口类型</label>
			<div class="col-sm-8"><label style="font-weight: normal;"><input type="radio" id="apiType10" name="apiType" class="" onclick="info.changeApiType($(this).val())" value="10"> URL</label>&nbsp;&nbsp;
				<label style="font-weight: normal;"><input type="radio" id="apiType20" name="apiType" class="" onclick="info.changeApiType($(this).val())" value="20" checked="checked"> 服务</label>&nbsp;&nbsp;
				<div id="apiServicePanel" style="display: block;">
					<table>
						<tr>
						<td style="width: 80px;padding: 3px;">
							<input type="text" class="form-control input-sm" id="prjName" placeholder="服务名称" value="" onblur="info.changePrj()" autocomplete="off"/>
							<input type="hidden" id="prjId"/>
						</td>
						<td style="width: 200px;padding: 3px;">
							<input type="text" class="form-control input-sm" id="pathName" placeholder="接口地址" value="" autocomplete="off" />
							<input type="hidden" id="path" value=""/>
						</td>
						<td style="padding: 3px;"><a href="javascript:info.addApi('20');" class="text-success"><small>添加</small></a></td>
						</tr>
					</table>
				</div>
				<div id="apiUrlPanel" style="display: none;">
					<table>
						<tr>
						<td style="width: 280px;padding: 3px;">
							<input type="text" class="form-control input-sm" id="apiUrl" placeholder="接口地址" value="" />
						</td>
						<td style="padding: 3px;"><a href="javascript:info.addApi('10');" class="text-success"><small>添加</small></a></td>
						</tr>
					</table>
				</div>
			</div>
		</div>
		<table class="table table-striped table-hover">
			<thead>
			<tr class="info">
                     <th width="130">服务</th>
                     <th width="280">接口名称或地址</th>
                     <th width="60">操作</th>
			</tr>
            </thead>
            <tbody id="paramsTbody"></tbody>
		</table>
		
  		<div class="footer-operate">
			<span id="saveMsg" class="label label-danger"></span>
 			<div class="btn-group">
				<button type="button" id="saveBtn" class="btn btn-success enter-fn">保存</button>
			</div>
		</div>
	</div>

	<jsp:include page="/WEB-INF/view/inc/js.jsp"></jsp:include>
	<script type="text/javascript">
	var info = {
			addApi: function(type) {
				var saveMsg = $('#saveMsg').empty();
				var prjId = '';
				var prjName = '';
				var path = '';
				var pathName = '';
				if (type == '20') {
					prjName = $('#prjName').val();
					if (prjName == '') {
						saveMsg.append('请选择服务');
						return;
					}
					prjId = $('#prjId').val();
					path = $('#path').val();
					if (path == '') {
						saveMsg.append('请选择接口');
						return;
					}
					pathName = $('#pathName').val();
					$('#pathName').val('');
					$('#path').val('');
				} else {
					path = $('#apiUrl').val();
					pathName = path;
					$('#apiUrl').val('');
				}
				var item = {
						prjId: prjId, prjName: prjName, path: path, pathName: pathName
				};
				info.addApiItem(item);
			},
			apiList: [],
			addApiItem: function(item) {
				var paramsTbody = $('#paramsTbody');
				var content = [];
				content.push('<tr>',
						'<td>',item.prjName,'</td>',
						'<td>',item.pathName,'</td>',
						'<td><a class="glyphicon glyphicon-remove text-success" href="javascript:;" onclick="info.delApiItem(this)" title="删除"></a></td>',
						'</tr>');
				paramsTbody.append(content.join(''));
				info.apiList.push(item);
			},
			delApiItem: function(_this) {
				$(_this).parent().parent().remove();
			},
			changeApiType: function(val) {
				if (val == '20') {
					$('#apiServicePanel').css('display', 'block');
					$('#apiUrlPanel').css('display', 'none');
				} else {
					$('#apiServicePanel').css('display', 'none');
					$('#apiUrlPanel').css('display', 'block');
				}
			},
			changePrj: function() {
				var prjId = $('#prjId').val();
				if (JUtil.isEmpty(prjId)) {
					return;
				}
				$('#pathName').typeahead('destroy');
				JUtil.sys.typeahead({
					id: 'pathName',
					valueId: 'path',
					url: webroot + '/prjApi/f-json/findSearch?type=kvEntity&prjId=' + prjId
				});
			},
			changeType: function(val) {
				if (val == '20') {
					$('#imgPanel').css('display', 'block');
					$('#urlPanel').css('display', 'none');
				} else {
					$('#imgPanel').css('display', 'none');
					$('#urlPanel').css('display', 'block');
					$('#urlValue').val('${appAnt.typeValue}');
				}
			},
			uploadBase64Img: function(imgstr) {
				var saveMsg = $('#saveMsg').empty();
				JUtil.ajax({
					url : '${webroot}/sysFile/f-json/uploadBase64.shtml',
					data : { imgstr: imgstr, type: 20 },
					success : function(json) {
						if (json.code === 0) {
							saveMsg.append('上传图片成功');
							$('#typeValue').val(json.body.url);
							$('#imgFile').attr('src', '${webroot}/sysFile/f-view/preview.shtml?url='+json.body.url);
						}
						else if (json.code === -1)
							saveMsg.append(JUtil.msg.ajaxErr);
						else
							saveMsg.append(json.message);
					}
				});
			}
	};
	
	$(function() {
		if ('${appAnt.parentAaId}' == '') {
			$('#parentAaId').val('${param.parentAaId}');
		} else {
			info.changeType('${appAnt.type}');
			if ('${appAnt.typeValue}' != '') {
				$('#imgFile').attr('src', '${webroot}/sysFile/f-view/preview.shtml?url=${appAnt.typeValue}');
			}
			var apiInfoString = '${appAnt.apiInfo}';
			if (apiInfoString != '') {
				var apiInfo = $.parseJSON(apiInfoString);
				$.each(apiInfo, function(i, item) {
					info.addApiItem(item);
				});
			}
		}

		JUtil.sys.typeahead({
			id: 'prjName',
			valueId: 'prjId',
			url: webroot + '/appInfo/f-json/findSearchPrj?aiId=${param.aiId}'
		});
		
		$('#saveBtn').click(function() {
			var saveMsg = $('#saveMsg').empty();
			var name = $('#name');
			if(JUtil.isEmpty(name.val())) {
				saveMsg.append('请输入名称');
				name.focus();
				return;
			}
			var typeValue = '';
			var type = $('input[name="type"]:checked').val();
			if (type == '10') {
				typeValue = $('#urlValue').val();
			} else {
				typeValue = $('#typeValue').val();
			}

			JUtil.ajax({
				eventId: 'saveBtn',
				url: '${webroot}/appAnt/f-json/save',
				data: {
					aiId: $('#aiId').val(),
					aaId: $('#aaId').val(),
					parentAaId: $('#parentAaId').val(),
					name: name.val(),
					remark: $('#remark').val(),
					type: type,
					typeValue: typeValue,
					apiInfo: JSON.stringify(info.apiList)
				},
				success : function(json) {
					if (json.code === 0) {
						saveMsg.attr('class', 'label label-success').append('保存成功');
						setTimeout(function() {
							parent.antInfo.loadInfo();
							parent.dialog.close();
						}, 800);
					}
					else if (json.code === -1)
						saveMsg.append(JUtil.msg.ajaxErr);
					else
						saveMsg.append(json.message);
				}
			});
		});
	});

	document.addEventListener('paste', function (event) {
		// 处理粘贴事件
	 	console.log(event);
		var imgPasteId = event.srcElement.id;
		if (imgPasteId != 'imgPaste') {
			console.log('没有在输入框粘贴');
			return;
		}
		var isChrome = false;
		  if ( event.clipboardData || event.originalEvent ) {
		    //not for ie11  某些chrome版本使用的是event.originalEvent
		    var clipboardData = (event.clipboardData || event.originalEvent.clipboardData);
		    if ( clipboardData.items ) {
		      // for chrome
		      var  items = clipboardData.items,
		        len = items.length,
		        blob = null;
		      isChrome = true;
		      //items.length比较有意思，初步判断是根据mime类型来的，即有几种mime类型，长度就是几（待验证）
		      //如果粘贴纯文本，那么len=1，如果粘贴网页图片，len=2, items[0].type = 'text/plain', items[1].type = 'image/*'
		      //如果使用截图工具粘贴图片，len=1, items[0].type = 'image/png'
		      //如果粘贴纯文本+HTML，len=2, items[0].type = 'text/plain', items[1].type = 'text/html'
		      //阻止默认行为即不让剪贴板内容在div中显示出来
		      event.preventDefault();
		      //在items里找粘贴的image,据上面分析,需要循环  
		      for (var i = 0; i < len; i++) {
		        if (items[i].type.indexOf("image") !== -1) {
		          // console.log(items[i]);
		          // console.log( typeof (items[i]));

		          //getAsFile() 此方法只是living standard firefox ie11 并不支持        
		          blob = items[i].getAsFile();
		        }
		      }
		      if ( blob !== null ) {
		        var reader = new FileReader();
		        reader.onload = function (event) {
		          // event.target.result 即为图片的Base64编码字符串
		          var base64Str = event.target.result
		          //可以在这里写上传逻辑 直接将base64编码的字符串上传（可以尝试传入blob对象，看看后台程序能否解析）
		          info.uploadBase64Img(base64Str);
		        }
		        reader.readAsDataURL(blob); 
		      }
		    }
		  }
	});
	</script>
</body>
</html>